package com.huge.rpc.client.Impl;

import com.huge.rpc.Peer;
import com.huge.rpc.client.TransportClient;
import com.huge.rpc.common.constanst.HttpCommon;
import com.huge.rpc.common.constanst.RequestMethod;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author jihu
 * @date 2020/10/12
 */
public class HttpTransportClient implements TransportClient {

    private String url;

    @Override
    public void connect(Peer peer) {
        this.url = generateUrl(peer);
    }

    /**
     * 根据Peer生成URL
     * @param peer
     * @return
     */
    private String generateUrl(Peer peer) {
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(HttpCommon.URL_PREFIX)
                  .append(peer.getHost())
                  .append(HttpCommon.URL_APPEND)
                  .append(peer.getPort());
        return urlBuilder.toString();
    }

    @Override
    public InputStream write(InputStream data) {
        try {
            HttpURLConnection httpConnection = openConnection(data);

            int resultCode = httpConnection.getResponseCode();

            if(resultCode == httpConnection.HTTP_OK){
                return httpConnection.getInputStream();
            }else {
                return httpConnection.getErrorStream();
            }

        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * 根据 url 和 二进制数据 建立连接
     * @param data
     * @return
     * @throws IOException
     */
    private HttpURLConnection openConnection(InputStream data) throws IOException {
        HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);
        httpConnection.setUseCaches(false);
        httpConnection.setRequestMethod(RequestMethod.POST);
        httpConnection.connect();
        IOUtils.copy(data,httpConnection.getOutputStream());
        return httpConnection;
    }

    @Override
    public void close() {

    }
}
